package com.ewili.x.special.task.thread.impl;

import com.ewili.framework.utils.CollectionUtils;
import com.ewili.framework.utils.ExcelUtils;
import com.ewili.framework.utils.HttpClientUtils;
import com.ewili.framework.utils.StringUtils;
import com.ewili.x.special.dao.inter.HisRecordDao;
import com.ewili.x.special.dao.inter.StockDao;
import com.ewili.x.special.entity.HisRecord;
import com.ewili.x.special.service.data.inter.StockService;
import com.ewili.x.special.task.thread.inter.StockThreadTask;
import com.ewili.x.special.vo.HisRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wonder
 */
@Slf4j
@Component
public class StockThreadTaskImpl implements StockThreadTask {

    @Autowired
    private HisRecordDao hisRecordDao;

    @Autowired
    private StockDao stockDao;

    @Autowired
    private StockService stockService;


    //http://finance.sina.com.cn/realstock/company/sz002095/houfuquan.js?d=2015-06-16
    //@Async("myTaskAsyncPool")
    @Override
    public void spideHisRecord(HisRecordVo hisRecordVo) {
        try {
            String content = HttpClientUtils.getContent(hisRecordVo.getUrl(), 30000000, 30000000);
            doSpideHisRecord(content, hisRecordVo.getStockCode());
        } catch (Exception e) {
            log.error("url:{}", hisRecordVo, e);
        }
    }

    //@Async("myTaskAsyncPool")
    @Override
    public void spideAdj(String url) {
        try {
            String code = stockService.getCodeFromUrl(url, "http://finance.sina.com.cn/realstock/company/", "/qianfuquan.js", true);
            List<HisRecord> hisRecords = hisRecordDao.findHisRecordByStockCodeAndAdj(code, 0);
            if (CollectionUtils.isEmpty(hisRecords)) {
                return;
            }
            String content = HttpClientUtils.getContent(url, 3000000, 300000);
            if (StringUtils.contains(content, "{_")) {
                content = StringUtils.substring(content, "data:", "}]").replaceAll("data:", "");
                content = content.replace("(", "").replace("}", "").replace("{", "");
                String[] contentArr = content.split(",");
                ArrayList<HisRecord> hisRecordAds = new ArrayList<HisRecord>();
                for (int i = 0; i < contentArr.length; i++) {
                    String[] strArr = contentArr[i].split(":");
                    String dateStr = strArr[0].replaceFirst("_", "").replace("_", "-");
                    String adjStr = strArr[1].replaceAll("\"", "");
                    Date date = DateUtils.parseDate(dateStr, com.ewili.framework.utils.DateUtils.yyyy_MM_dd);
                    Double adj = Double.valueOf(adjStr);
                    for (int j = 0; j < hisRecords.size(); j++) {
                        HisRecord record = hisRecords.get(j);
                        if (DateUtils.isSameDay(date, record.getDate()) && record.getAdj() == 0) {
                            record.setAdj(adj);
                            hisRecordAds.add(record);
                            break;
                        }
                    }

                }
                hisRecordDao.saveAll(hisRecordAds);

            }
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    // @Async("myTaskAsyncPool")
    void doSpideHisRecord(String content, String stockCode) throws Exception {
        List<List<String>> hisRecordRows = ExcelUtils.readCSV(content);
        List<HisRecord> hisRecordHad = hisRecordDao.findHisRecordByStockCodeOrderByDateDesc(stockCode);
        List<HisRecord> hisRecords = new ArrayList<>();
        for (int i = 1; i < hisRecordRows.size(); i++) {
            List<String> recordCells = hisRecordRows.get(i);

            if (StringUtils.contains(recordCells.get(8), "None") || StringUtils.equals(recordCells.get(11), "0") || StringUtils.equals(recordCells.get(14), "0") || StringUtils.contains(recordCells.get(10), "None")) {
                continue;
            }


            Date hisRecordDate = DateUtils.parseDate(recordCells.get(0), com.ewili.framework.utils.DateUtils.yyyy_MM_dd);

            if (hadHisRecord(stockCode, hisRecordDate, hisRecordHad)) {
                continue;
            }

            HisRecord hisRecord = new HisRecord();
            hisRecord.setDate(hisRecordDate);
            hisRecord.setStockCode(stockCode);
            hisRecord.setClose(Double.valueOf(recordCells.get(3)));
            hisRecord.setHigh(Double.valueOf(recordCells.get(4)));
            hisRecord.setLow(Double.valueOf(recordCells.get(5)));
            hisRecord.setOpen(Double.valueOf(recordCells.get(6)));
            hisRecord.setRefClose(Double.valueOf(recordCells.get(7)));
            hisRecord.setXchange(Double.valueOf(recordCells.get(8)));
            hisRecord.setChg(Double.valueOf(recordCells.get(9)));
            hisRecord.setExchangeRate(Double.valueOf(recordCells.get(10)));
            hisRecord.setVol(Double.valueOf(recordCells.get(11)));
            hisRecord.setAmount(Double.valueOf(recordCells.get(12)));
            hisRecord.setTotalValue(Double.valueOf(recordCells.get(13)));
            hisRecord.setCirculationValue(Double.valueOf(recordCells.get(14)));


            hisRecords.add(hisRecord);
        }
        hisRecordDao.saveAll(hisRecords);


    }


    private boolean hadHisRecord(String stockCode, Date date, List<HisRecord> hisRecords) {
        for (int i = 0; i < hisRecords.size(); i++) {
            if (hisRecords.get(i).getStockCode().equals(stockCode) && DateUtils.isSameDay(hisRecords.get(i).getDate(), date)) {
                return true;
            }
        }
        return false;
    }
}
